package com.example.springboot3demo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class WindSessionIdEncryptUtil {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(WindSessionIdEncryptUtil.class);

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    private static final String SECRET_KEY = "BondAccessRecord2024SecretKey";

    public static String encryptSessionId(String sessionId) {
        if (StringUtils.isEmpty(sessionId)) {
            return sessionId;
        }
        try {
            SecretKeySpec secretKey = generateSecretKey();
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(sessionId.getBytes(StandardCharsets.UTF_8));
            String encryptedRecordId = Base64.encodeBase64String(encryptedBytes);
            log.debug("SessionId加密成功，原始长度: {}, 加密后长度: {}", sessionId.length(), encryptedRecordId.length());
            return encryptedRecordId;
        } catch (Exception e) {
            log.error("SessionId加密失败，返回原始值: {}", e.getMessage(), e);
            return sessionId;
        }
    }

    public static String decryptRecordId(String recordId) {
        if (StringUtils.isEmpty(recordId)) {
            return recordId;
        }
        try {
            SecretKeySpec secretKey = generateSecretKey();
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] encryptedBytes = Base64.decodeBase64(recordId);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            String decryptedSessionId = new String(decryptedBytes, StandardCharsets.UTF_8);
            log.debug("RecordId解密成功，加密长度: {}, 解密后长度: {}", recordId.length(), decryptedSessionId.length());
            return decryptedSessionId;
        } catch (Exception e) {
            log.error("RecordId解密失败，返回原始值: {}", e.getMessage(), e);
            return recordId;
        }
    }

    private static SecretKeySpec generateSecretKey() {
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            byte[] keyBytes = sha.digest(SECRET_KEY.getBytes(StandardCharsets.UTF_8));
            byte[] aesKey = new byte[16];
            System.arraycopy(keyBytes, 0, aesKey, 0, 16);
            return new SecretKeySpec(aesKey, ALGORITHM);
        } catch (Exception e) {
            log.error("生成密钥失败", e);
            throw new RuntimeException("生成加密密钥失败", e);
        }
    }

    public static boolean validateEncryptDecrypt(String originalText) {
        try {
            String encrypted = encryptSessionId(originalText);
            String decrypted = decryptRecordId(encrypted);
            boolean isValid = originalText.equals(decrypted);
            log.info("加密解密验证结果: {}, 原始: {}, 加密: {}, 解密: {}", isValid, originalText, encrypted, decrypted);
            return isValid;
        } catch (Exception e) {
            log.error("验证加密解密失败", e);
            return false;
        }
    }

    public static boolean isEncryptedFormat(String text) {
        if (StringUtils.isEmpty(text)) {
            return false;
        }
        try {
            byte[] decoded = Base64.decodeBase64(text);
            return decoded.length > 0 && decoded.length % 16 == 0;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println(decryptRecordId("G/gysbeJxUKHc+B3FEWZG6AZci969yz6LrVEugjCkwS8ekxTdQP/J2a2FHFdTbsN"));

    }

}